<template>
  <tn-navbar :bottom-shadow="false" fixed >
    <text class="title">通知设置</text>
  </tn-navbar>
  <view class="container">
    <view class="settings-card">
      <view class="section-header">
        <text class="section-title">通知方式</text>
      </view>
      
      <view class="setting-item">
        <text class="setting-label">小程序通知</text>
        <switch 
          :checked="settings.miniProgramNotify" 
          @change="onMiniProgramNotifyChange" 
          color="#1aad19"
        />
      </view>
      
      <view class="setting-item" v-if="settings.botWechatStatus">
        <text class="setting-label">微信机器人通知</text>
        <switch 
          :checked="settings.wechatNotify" 
          @change="onWechatNotifyChange" 
          color="#1aad19"
        />
      </view>
      
      <view class="bot-binding" v-if="settings.wechatNotify && settings.botWechatStatus  && !settings.bindBotStatus">
        <view class="binding-steps">
          <text class="binding-title">请按以下步骤绑定微信机器人：</text>
          <view class="binding-step">
            <text>1. 长按下方二维码保存并添加机器人为好友</text>
            <view class="qrcode-container">
              <image class="qrcode-image" :src="settings.botWechatId" mode="aspectFit" @tap="previewQRCode"></image>
            </view>
          </view>
          <view class="binding-step">
            <text>2. 复制下方绑定码，发送给机器人</text>
            <view class="binding-code-container">
              <text class="binding-code">{{ settings.bindingCode }}</text>
              <button class="copy-btn" size="mini" @tap="copyBindingCode">复制</button>
            </view>
          </view>
        </view>
        <view class="binding-status">
          <text class="status-text">绑定状态：{{ settings.bindBotStatus ? '已绑定' : '未绑定' }}</text>
          <button class="refresh-btn" size="mini" @tap="refreshBindStatus">刷新状态</button>
        </view>
      </view>
    </view>
    
    <view class="settings-card">
      <view class="section-header">
        <text class="section-title">免打扰时间</text>
        <switch 
          :checked="settings.enableDoNotDisturb" 
          @change="onDoNotDisturbChange" 
          color="#1aad19"
          class="section-switch"
        />
      </view>
      
      <template v-if="settings.enableDoNotDisturb">
        <view class="setting-item">
          <text class="setting-label">开始时间</text>
          <picker 
            mode="time" 
            :value="settings.doNotDisturbStart" 
            @change="onStartTimeChange"
            class="time-picker"
          >
            <view class="picker-value">{{ settings.doNotDisturbStart }}</view>
          </picker>
        </view>
        
        <view class="setting-item">
          <text class="setting-label">结束时间</text>
          <picker 
            mode="time" 
            :value="settings.doNotDisturbEnd" 
            @change="onEndTimeChange"
            class="time-picker"
          >
            <view class="picker-value">{{ settings.doNotDisturbEnd }}</view>
          </picker>
        </view>
        
        <view class="setting-desc">
          <text>在免打扰时间内，您将不会收到挪车通知</text>
        </view>
      </template>
    </view>
    
    <view class="settings-card">
      <view class="section-header">
        <text class="section-title">Webhook通知</text>
        <switch 
          :checked="settings.webhookNotify" 
          @change="onWebhookNotifyChange" 
          color="#1aad19"
        />
      </view>
      
      <view v-if="settings.webhookNotify">
        <view class="webhook-header">
          <view class="webhook-desc-wrap">
            <text class="webhook-desc">可配置最多3个Webhook地址接收通知，支持企业微信机器人，钉钉机器人(添加关键词`挪车`)，自定义Webhook地址</text>
          </view>
          <button 
            class="add-webhook-btn" 
            size="mini" 
            @tap="addWebhook"
            :disabled="settings.webhooks.length >= 3"
          >添加</button>
        </view>
        
        <view 
          class="webhook-item" 
          v-for="(webhook, index) in settings.webhooks" 
          :key="index"
        >
          <view class="webhook-input">
            <input 
              type="text" 
              v-model="webhook.url" 
              placeholder="请输入Webhook地址"
            />
          </view>
          <view class="webhook-actions">
            <button class="test-btn" size="mini" @tap="testWebhook(index)">测试</button>
            <button class="delete-btn" size="mini" @tap="deleteWebhook(index)">删除</button>
          </view>
        </view>
      </view>
    </view>
    
    <view class="save-button">
      <button class="save-btn" @tap="saveSettings">保存设置</button>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue';

// 添加模拟数据 - 设置信息
const mockSettingsData = {
  code: 200,
  msg: "success",
  data: {
    miniProgramNotify: true,
    wechatNotify: true,
    bindBotStatus: false,
    webhookNotify: true,
    webhooks: [
      {url: "https://oapi.amsss.com"},
      {url: "https://oapi.dingtalk.com/robot/send?access_token="},
      {url: "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key="}
    ],
    enableDoNotDisturb: true,
    doNotDisturbStart: "23:59",
    doNotDisturbEnd: "00:00",
    bindingCode: "CCz487f4",
    botWechatId: "https://pro-cdn.bugjianghu.com/250316/pub_67d6c22af16b20.20807411.jpg",
    botWechatStatus: true
  },
  timestamp: 1742879886
};

// 设置数据
const settings = ref({
  miniProgramNotify: false,
  wechatNotify: false,
  bindBotStatus: false,
  botWechatId: '',
  bindingCode: '',
  webhookNotify: false,
  botWechatStatus: false,
  webhooks: [],
  enableDoNotDisturb: false,
  doNotDisturbStart: '22:00',
  doNotDisturbEnd: '08:00'
});

// 页面加载时获取设置
onMounted(() => {
  getSettings();
});

// 获取设置
const getSettings = async () => {
  try {
    // 使用模拟数据替代API调用
    setTimeout(() => {
      // 设置数据
      const data = mockSettingsData.data;
      settings.value = {
        miniProgramNotify: data.miniProgramNotify,
        wechatNotify: data.wechatNotify,
        bindBotStatus: data.bindBotStatus,
        botWechatId: data.botWechatId,
        bindingCode: data.bindingCode,
        webhookNotify: data.webhookNotify,
        botWechatStatus: data.botWechatStatus,
        webhooks: data.webhooks || [],
        enableDoNotDisturb: data.enableDoNotDisturb,
        doNotDisturbStart: data.doNotDisturbStart,
        doNotDisturbEnd: data.doNotDisturbEnd
      };
    }, 500);
  } catch (error) {
    console.error('获取设置失败:', error);
  }
};

// 小程序通知开关变化
const onMiniProgramNotifyChange = async (e) => {
  const isChecked = e.detail.value;
  settings.value.miniProgramNotify = isChecked;
  if (isChecked) {
    try {
      // // 获取订阅消息模板列表
      // const templates =  uni.getStorageSync('subMessageTemplateList');
      // // 调用小程序订阅消息接口
      // const result = await uni.requestSubscribeMessage({
      //   tmplIds: templates
      // });
      // // 根据订阅结果处理
      // if (result.errMsg === 'requestSubscribeMessage:ok') {
      //   // 检查每个模板的订阅状态
      //   console.log(result,'resultresult')
      //   const hasRejected = Object.values(result).includes('reject');
      //   if (hasRejected) {
      //     uni.showToast({
      //       title: '部分消息订阅被拒绝',
      //       icon: 'none'
      //     });
      //     settings.value.miniProgramNotify = false;
      //   }
      // }
    } catch (error) {
      console.error('订阅消息失败:', error);
      uni.showToast({
        title: '订阅消息失败',
        icon: 'none'
      });
      settings.value.miniProgramNotify = false;
    }
  }
};

// 微信通知开关变化
const onWechatNotifyChange = async (e) => {
  settings.value.wechatNotify = e.detail.value;

};

// 刷新绑定状态
const refreshBindStatus = async () => {
  uni.showLoading({
    title: '刷新中...'
  });
  
  try {
    // 使用模拟数据替代API调用
    setTimeout(() => {
      // 随机模拟绑定状态
      const newStatus = Math.random() > 0.5;
      settings.value.bindBotStatus = newStatus;
      mockSettingsData.data.bindBotStatus = newStatus;
      
      uni.hideLoading();
      uni.showToast({
        title: newStatus ? '已绑定' : '未绑定',
        icon: newStatus ? 'success' : 'none'
      });
    }, 1000);
  } catch (error) {
    uni.hideLoading();
    console.error('刷新绑定状态失败:', error);
    uni.showToast({
      title: '刷新失败',
      icon: 'none'
    });
  }
};


// Webhook相关方法
const addWebhook = () => {
  if (settings.value.webhooks.length >= 3) {
    uni.showToast({
      title: '最多添加3个Webhook',
      icon: 'none'
    });
    return;
  }
  settings.value.webhooks.push({ url: '' });
};

const deleteWebhook = (index) => {
  settings.value.webhooks.splice(index, 1);
};

const testWebhook = async (index) => {
  const webhook = settings.value.webhooks[index];
  if (!webhook || !webhook.url) {
    uni.showToast({
      title: '请输入有效的Webhook地址',
      icon: 'none'
    });
    return;
  }
  
  uni.showLoading({
    title: '测试中...'
  });
  
  try {
    // 使用模拟数据替代API调用
    setTimeout(() => {
      // 随机模拟测试结果
      const success = Math.random() > 0.3;
      
      uni.hideLoading();
      uni.showToast({
        title: success ? '测试成功' : '测试失败',
        icon: success ? 'success' : 'none'
      });
    }, 1500);
  } catch (error) {
    uni.hideLoading();
    console.error('测试Webhook失败:', error);
    uni.showToast({
      title: '测试失败',
      icon: 'none'
    });
  }
};

// 免打扰开关变化
const onDoNotDisturbChange = (e) => {
  settings.value.enableDoNotDisturb = e.detail.value;
};

// 开始时间变化
const onStartTimeChange = (e) => {
  settings.value.doNotDisturbStart = e.detail.value;
};

// 结束时间变化
const onEndTimeChange = (e) => {
  settings.value.doNotDisturbEnd = e.detail.value;
};

// webhook通知开关变化
const onWebhookNotifyChange = (e) => {
  settings.value.webhookNotify = e.detail.value;
};

// 预览二维码
const previewQRCode = () => {
  uni.previewImage({
    urls: [settings.value.botWechatId],
    current: settings.value.botWechatId
  });
};

// 复制绑定码
const copyBindingCode = () => {
  uni.setClipboardData({
    data: settings.value.bindingCode,
    success: () => {
      uni.showToast({
        title: '绑定码已复制',
        icon: 'success'
      });
    }
  });
};

// 保存设置
const saveSettings = async () => {
  uni.showLoading({
    title: '保存中...'
  });
  
  try {
    // 使用模拟数据替代API调用
    setTimeout(() => {
      // 更新模拟数据
      mockSettingsData.data = {
        ...mockSettingsData.data,
        miniProgramNotify: settings.value.miniProgramNotify,
        wechatNotify: settings.value.wechatNotify,
        webhookNotify: settings.value.webhookNotify,
        webhooks: settings.value.webhooks,
        enableDoNotDisturb: settings.value.enableDoNotDisturb,
        doNotDisturbStart: settings.value.doNotDisturbStart,
        doNotDisturbEnd: settings.value.doNotDisturbEnd
      };
      
      uni.hideLoading();
      uni.showToast({
        title: '保存成功',
        icon: 'success'
      });
    }, 1000);
  } catch (error) {
    uni.hideLoading();
    console.error('保存设置失败:', error);
    uni.showToast({
      title: '保存失败',
      icon: 'none'
    });
  }
};
</script>

<style>
.container {
  padding: 20rpx;
}

.settings-card {
  background-color: #ffffff;
  border-radius: 12rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
  padding: 30rpx;
  margin-bottom: 30rpx;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.section-switch {
  transform: scale(0.8);
}

.setting-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
}

.setting-item:last-child {
  border-bottom: none;
}

.setting-label {
  font-size: 28rpx;
  color: #333;
}

.setting-value {
  font-size: 28rpx;
  color: #666;
}

.phone-value {
  display: flex;
  align-items: center;
}

.edit-text {
  color: #1989fa;
  margin-left: 20rpx;
  font-size: 24rpx;
}

.time-picker, .sound-picker {
  min-width: 200rpx;
  text-align: right;
}

.picker-value {
  font-size: 28rpx;
  color: #666;
}

.setting-desc {
  font-size: 24rpx;
  color: #999;
  padding: 20rpx 0 0;
}

.save-button {
  margin-top: 50rpx;
  padding: 0 30rpx;
}

.save-btn {
  background-color: #1aad19;
  color: white;
  height: 80rpx;
  line-height: 80rpx;
  font-size: 30rpx;
  border-radius: 8rpx;
}

.bot-binding {
  padding: 20rpx;
  background-color: #f8f8f8;
  border-radius: 8rpx;
  margin-top: 20rpx;
}

.binding-steps {
  margin-bottom: 20rpx;
}

.binding-title {
  font-size: 28rpx;
  color: #333;
  margin-bottom: 10rpx;
  display: block;
}

.binding-step {
  font-size: 26rpx;
  color: #666;
  display: block;
  margin-top: 20rpx;
}

.binding-status {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.status-text {
  font-size: 26rpx;
  color: #666;
}

.refresh-btn {
  font-size: 24rpx;
  padding: 0 20rpx;
}

.webhook-section {
  margin-top: 30rpx;
}

.webhook-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 20rpx;
  gap: 20rpx;
}

.webhook-desc-wrap {
  flex: 1;
  margin-right: 20rpx;
}

.webhook-desc {
  font-size: 26rpx;
  color: #666;
  line-height: 1.4;
  display: block;
}

.add-webhook-btn {
  font-size: 24rpx;
  flex-shrink: 0;
  min-width: 100rpx;
  margin-top: 4rpx;
}

.webhook-item {
  margin-bottom: 20rpx;
  padding: 20rpx;
  background-color: #f8f8f8;
  border-radius: 8rpx;
}

.webhook-input {
  margin-bottom: 10rpx;
}

.webhook-input input {
  width: 100%;
  height: 60rpx;
  padding: 0 20rpx;
  font-size: 26rpx;
  background-color: #fff;
  border-radius: 4rpx;
}

.webhook-actions {
  display: flex;
  justify-content: flex-end;
  gap: 20rpx;
}

.test-btn, .delete-btn {
  font-size: 24rpx;
}

.delete-btn {
  background-color: #ff4d4f;
  color: #fff;
}

.qrcode-container {
  margin: 20rpx 0;
  display: flex;
  justify-content: center;
}

.qrcode-image {
  width: 300rpx;
  height: 300rpx;
  background-color: #f0f0f0;
}

.binding-code-container {
  display: flex;
  align-items: center;
  margin-top: 10rpx;
  background-color: #f0f0f0;
  padding: 10rpx 20rpx;
  border-radius: 6rpx;
}

.binding-code {
  flex: 1;
  font-size: 28rpx;
  color: #333;
  font-weight: bold;
}

.copy-btn {
  margin-left: 20rpx;
  font-size: 24rpx;
  background-color: #1aad19;
  color: white;
}
</style> 